package org.nfyszny.zzzs.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.nfyszny.zzzs.modules.constant.CertificateConstant;
import org.nfyszny.zzzs.modules.constant.ExamineConstant;
import org.nfyszny.zzzs.modules.constant.ReCordConstant;
import org.nfyszny.zzzs.modules.entity.*;
import org.nfyszny.zzzs.modules.mapper.ZzzsExamineMapper;
import org.nfyszny.zzzs.modules.service.*;
import org.nfyszny.zzzs.modules.utils.PdfUtil;
import org.nfyszny.zzzs.modules.utils.UserUtils;
import org.nfyszny.zzzs.modules.vo.ExamineRecordVo;
import org.nfyszny.zzzs.modules.vo.TimeOutVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 审批表
 * @Author: jeecg-boot
 * @Date: 2022-11-14
 * @Version: V1.0
 */
@Service
public class ZzzsExamineServiceImpl extends ServiceImpl<ZzzsExamineMapper, ZzzsExamine> implements IZzzsExamineService {
    @Autowired
    @Lazy
    private IZzzsRecordEnterpriseService enterpriseService;
    @Autowired
    @Lazy
    private IZzzsProductRecordingService recordingService;
    @Autowired
    @Lazy
    private IZzzsRecordingOfProductionCapacityService productionCapacityService;
    @Autowired
    @Lazy
    private IZzzsRecordOfSupplyAbilityService supplyAbilityService;
    @Autowired
    private IZzzsCertificateService certificateService;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private ISysUserService userService;
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Override

    public Boolean checkStatus(String id) {

        ZzzsExamine zzzsExamine = baseMapper.selectById(id);
        return zzzsExamine.getExamineStatus() == ExamineConstant.StatusEnum.CHECK_STATUS.getCode();
    }

    @Override
    public IPage<ZzzsExamine> selectExamineList(QueryWrapper<ZzzsExamine> queryWrapper, Page<ZzzsExamine> page) {
        LoginUser userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            if (!userInfo.getUsername().equals("root")) {
                queryWrapper.eq("examine_person", userInfo.getId());
            }
        }
        queryWrapper.and(item -> {
            item.eq("examine_status", ExamineConstant.StatusEnum.CHECK_STATUS.getCode())
                    .or().eq("examine_status", ExamineConstant.StatusEnum.CHECK_TIMEOUT.getCode());
        });
        return page(page, queryWrapper);
    }

    @Override
    public IPage<ZzzsExamine> selectRecorded(QueryWrapper<ZzzsExamine> queryWrapper, Page<ZzzsExamine> page) {
        LoginUser userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            if (!userInfo.getUsername().equals("root")) {
                queryWrapper.eq("examine_person", userInfo.getId());
            }
        }
        queryWrapper.and(item -> {
            item.eq("examine_status", ExamineConstant.StatusEnum.SUCCESS_STATUS.getCode())
                    .or().eq("examine_status", ExamineConstant.StatusEnum.ERROR_STATUS.getCode());
        });
        return page(page, queryWrapper);
    }

    @Override
    @Transactional
    public void examineRecord(ExamineRecordVo recordVo) {
        LoginUser userInfo = UserUtils.getUserInfo();
        String recordType = "";
        System.out.println("recordVo = " + recordVo);
        //1.修改审批表信息
        ZzzsExamine zzzsExamine = new ZzzsExamine();
        BeanUtils.copyProperties(recordVo, zzzsExamine);
        zzzsExamine.setExaminePerson(userInfo.getId());
        baseMapper.updateById(zzzsExamine);
        //判断备案是否通过
        int code = ReCordConstant.RecordEnum.RECORD_ERROR.getCode();
        if (recordVo.getExamineStatus() == ExamineConstant.StatusEnum.SUCCESS_STATUS.getCode()) {
            code = ReCordConstant.RecordEnum.RECORD_SUCCESS.getCode();
        }
        //2.判断是什么备案并更改相应的状态

        if (recordVo.getRecordType() == ExamineConstant.RecordType.ENTERPRISE_RECORD.getCode()) {
            ZzzsRecordEnterprise enterprise = new ZzzsRecordEnterprise();
            enterprise.setId(recordVo.getRecordId());
            enterprise.setStatus(code);
            enterpriseService.updateById(enterprise);
            recordType = ExamineConstant.RecordType.ENTERPRISE_RECORD.getMsg();
        } else if (recordVo.getRecordType() == ExamineConstant.RecordType.PRODUCT_RECORD.getCode()) {
            ZzzsProductRecording recording = new ZzzsProductRecording();
            recording.setId(recordVo.getRecordId());
            recording.setStatus(code);
            recordingService.updateById(recording);
            recordType = ExamineConstant.RecordType.PRODUCT_RECORD.getMsg();
        } else if (recordVo.getRecordType() == ExamineConstant.RecordType.PRODUCTION_CAPACITY_RECORD.getCode()) {
            ZzzsRecordingOfProductionCapacity capacity = new ZzzsRecordingOfProductionCapacity();
            capacity.setId(recordVo.getRecordId());
            capacity.setStatus(code);
            productionCapacityService.updateById(capacity);
            recordType = ExamineConstant.RecordType.PRODUCTION_CAPACITY_RECORD.getMsg();
        } else if (recordVo.getRecordType() == ExamineConstant.RecordType.CAPACITY_OF_EFFICACY_RECORD.getCode()) {
            ZzzsRecordOfSupplyAbility ability = new ZzzsRecordOfSupplyAbility();
            ability.setStatus(code);
            ability.setId(recordVo.getRecordId());
            recordType = ExamineConstant.RecordType.CAPACITY_OF_EFFICACY_RECORD.getMsg();
            supplyAbilityService.updateById(ability);
        }
        //3.生成证书
        if (code == ReCordConstant.RecordEnum.RECORD_SUCCESS.getCode()) {
            ZzzsCertificate certificate = new ZzzsCertificate();
            certificate.setCertificateId(recordVo.getRecordId());

            certificate.setStatus(CertificateConstant.CertificateStatus.GIVEN_OUT.getCode());
            certificate.setCertificateType(recordVo.getRecordType());
            System.out.println(userInfo);
            certificate.setApprover(userInfo.getRealname());
            certificate.setRecordTime(zzzsExamine.getUpdateTime());
            Calendar cal = Calendar.getInstance();
            cal.setTime(certificate.getRecordTime());
            cal.add(Calendar.YEAR, 1);
            certificate.setExpirationTime(cal.getTime());
            String pdfName = UUID.randomUUID().toString() + ".pdf";
            String bizPath = "/" + "pdf" + "/";
            File file = new File(uploadpath + bizPath);
            if (!file.exists()) {
                System.out.println("1111");
                file.mkdirs();
            }
            certificate.setCertificateUrl(bizPath + pdfName);
            certificateService.save(certificate);
            System.out.println("uploadpath = " + uploadpath);
            System.out.println(uploadpath + bizPath + pdfName);
            File saveFile = new File(uploadpath + bizPath + pdfName);
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("number", certificate.getId());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd");
            System.out.println("type" + recordType);
            dataMap.put("type", recordType);
            dataMap.put("recordTime", simpleDateFormat.format(certificate.getRecordTime()));
            Calendar c = Calendar.getInstance();
            c.setTime(certificate.getCreateTime());
            c.add(Calendar.YEAR, 1);
            dataMap.put("expirationTime", simpleDateFormat.format(c.getTime()));
            dataMap.put("checkTime", simpleDateFormat.format(certificate.getCreateTime()));
            dataMap.put("checkPerson", certificate.getCreateBy());
            System.out.println("dataMap = " + dataMap);
            try {
                Resource resource = new ClassPathResource("mb.pdf");
                String s = resource.getURI().toString();
                System.out.println("s = " + s);
                String substring = s.substring(s.indexOf("/") + 1);
                substring = substring.replace("!", "");

                String tempName = URLDecoder.decode(substring, "UTF-8");
                System.out.println("tempName=>" + tempName);
                PdfUtil.fillTemplate(dataMap, new FileOutputStream(saveFile), tempName);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<TimeOutVo> getYearTimeoutInfo(String year) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");

        LoginUser userInfo = UserUtils.getUserInfo();
        List<String> list = departService.selectLowerCode(userInfo.getId());
        System.out.println("list = " + list);
        if (StringUtils.isEmpty(year)) {
            System.out.println("year = " + year);
            List<TimeOutVo> timeOutVos = baseMapper.getYearTimeoutInfo(list, new Date(),userInfo.getId());
            return timeOutVos;
        } else {
            year = year.replace('"', ' ');
            System.out.println("year = " + year);
            System.out.println("simpleDateFormat.parse(year) = " + simpleDateFormat.parse(year));
            List<TimeOutVo> timeOutVos = baseMapper.getYearTimeoutInfo(list, simpleDateFormat.parse(year),userInfo.getId());
            return timeOutVos;
        }

    }

    @Override
    public List<TimeOutVo> getQuarteTimeoutInfo(String quarte) {

        LoginUser userInfo = UserUtils.getUserInfo();
        List<String> list = departService.selectLowerCode(userInfo.getId());
        System.out.println("list = " + list);
        List<TimeOutVo> timeOutVos = baseMapper.getQuarteTimeoutInfo(list, quarte,userInfo.getId());
        return timeOutVos;


    }

    @Override
    public List<TimeOutVo> getMonthTimeoutInfo(String date) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        LoginUser userInfo = UserUtils.getUserInfo();
        List<String> list = departService.selectLowerCode(userInfo.getId());
        System.out.println("list = " + list);
        if (StringUtils.isEmpty(date)) {

            List<TimeOutVo> timeOutVos = baseMapper.getMonthTimeoutInfo(list, new Date(),userInfo.getId());
            return timeOutVos;
        } else {
            date = date.replace('"', ' ');
            System.out.println("year = " + date);
            System.out.println("simpleDateFormat.parse(year) = " + simpleDateFormat.parse(date));
            List<TimeOutVo> timeOutVos = baseMapper.getMonthTimeoutInfo(list, simpleDateFormat.parse(date),userInfo.getId());
            return timeOutVos;
        }



    }


}
